import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_docmentstock_odoo_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_lendrecord_odoo_api.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_docmentstock.dart';
import 'package:flutter_admin/models/odoo/udt_tb_lendrecord.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/date_time_select.dart';
import 'package:flutter_admin/utils/utils.dart';
import '../../../generated/l10n.dart';
import 'package:intl/intl.dart';


class LendOrReturn extends StatefulWidget {
  LendOrReturn({this.udtTbDocmentstock});

  final UdtTbDocmentstock? udtTbDocmentstock;

  @override
  _LendOrReturnState createState() => _LendOrReturnState();
}

class _LendOrReturnState extends State<LendOrReturn> {
  late UdtTbLendrecord udtTbLendrecord;
  late UdtTbDocmentstock udtTbDocmentstock;
  bool? isAdd;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  late List<SelectOptionVO> activeList;

   //文档类别
  late List<SelectOptionVO> docmenttypeIdList = [];
   //人员名称
  late List<SelectOptionVO> userList = [];
  //部门
  late List<SelectOptionVO> workShopList = [];

  @override
  void initState() {
    super.initState();
    // this.isAdd = widget.udtTbLendrecord == null;
    this.udtTbDocmentstock = widget.udtTbDocmentstock ?? UdtTbDocmentstock();
    this.udtTbLendrecord = UdtTbLendrecord(
        documentno: udtTbDocmentstock.documentno,
        documentname: udtTbDocmentstock.documentname,
        departmentId: udtTbDocmentstock.departmentId,
        departmentName: udtTbDocmentstock.departmentName,
        documenttypeId:udtTbDocmentstock.documenttypeId,
        documenttypeName:udtTbDocmentstock.documenttypeName,
        areaId:udtTbDocmentstock.areaId,
        areaName:udtTbDocmentstock.areaName,
        locationId:udtTbDocmentstock.locationId,
        locationName:udtTbDocmentstock.locationName,
        remark:udtTbDocmentstock.remark,
    );
    _loadSelectVO();
  }

  _loadSelectVO() async{
   //借阅人员名称
   workShopList = await DynamicDataApi.getModelSelect(model: "hr.department",name: "complete_name",key: "parent_id",operator: "!=",val: null);
   activeList=[SelectOptionVO(value:'0',label: "禁用"),SelectOptionVO(value:'1',label: "启用")];
   if(udtTbDocmentstock.status == "1"){
     var lend = await UdtTbLendrecordOdooApi.getLend(documentno: udtTbDocmentstock.documentno);
     udtTbLendrecord.lenddeptId = lend[0]["lenddept_id"][0].toString();
     udtTbLendrecord.lenddeptName = lend[0]["lenddept_id"][1].toString();
     udtTbLendrecord.lenduserId = lend[0]["lenduser_id"][0].toString();
     udtTbLendrecord.lenduserName = lend[0]["lenduser_id"][1].toString();
     udtTbLendrecord.lenddate = Utils.getDate(date:lend[0]["lenddate"].toString());
     udtTbLendrecord.returndate = Utils.getDate();
   }else{
     udtTbLendrecord.lenddate = Utils.getDate();
   }
   setState(() { });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            label: '所属部门',
            enable: false,
            value: udtTbLendrecord.departmentName,
          ),
          CryInput(
            label: '档案项目',
            enable: false,
            value: udtTbLendrecord.documenttypeName,
          ),
          CryInput(
            label: '档案盒编号',
            enable: false,
            value: udtTbLendrecord.documentno,
          ),
          CryInput(
            label: '档案盒名称',
            enable: false,
            value: udtTbLendrecord.documentname,
          ),

          CryInput(
            label: '存放区域',
            enable: false,
            value: udtTbLendrecord.areaName,
          ),
          CryInput(
            label: '存放位置',
            enable: false,
            value: udtTbLendrecord.locationName,
          ),
          CryInput(
            label: '备注',
            enable: false,
            value: udtTbLendrecord.remark,
          ),

          udtTbDocmentstock.status=="1"?
          CryInput(
            label: '借阅部门',
            enable: false,
            value: udtTbLendrecord.lenddeptName,
          ):
          CrySelect(
            label: '借阅部门',
            value: udtTbLendrecord.lenddeptId,
            dataList: workShopList,
            onSaved: (v) {
              udtTbLendrecord.lenddeptId = v;
            },
            onChange: (v) async {
              if(udtTbLendrecord.lenddeptId!=v){
                formKey.currentState!.save();
                udtTbLendrecord.lenddeptId=v;
                udtTbLendrecord.lenduserId = null;
                try{
                  userList = await DynamicDataApi.getUserSelect(val: int.parse(v));
                }catch(e){
                  userList = [];
                }
                setState(() { });
              }
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          udtTbDocmentstock.status=="1"?
          CryInput(
            label: '借阅人员',
            enable: false,
            value: udtTbLendrecord.lenduserName,
          ):
          CrySelect(
            label: '借阅人员',
            dataList: userList,
            value: udtTbLendrecord.lenduserId,
            onSaved: (v) => { udtTbLendrecord.lenduserId = v},
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          udtTbDocmentstock.status=="1"?
          CryInput(
            label: '借阅时间',
            enable: false,
            value: udtTbLendrecord.lenddate,
          ):
          CrySelectDate(
            context,
            label: '借阅时间',
            value: udtTbLendrecord.lenddate,
            onSaved: (v) {
              udtTbLendrecord.lenddate = v;
            },
          ),

          udtTbDocmentstock.status=="1"?
          CrySelect(
            label: '归还部门',
            value: udtTbLendrecord.returndeptId,
            dataList: workShopList,
            onSaved: (v) {
              udtTbLendrecord.returndeptId = v;
            },
            onChange: (v) async {
              if(udtTbLendrecord.returndeptId!=v){
                formKey.currentState!.save();
                udtTbLendrecord.returndeptId=v;
                udtTbLendrecord.returnuserId = null;
                try{
                  userList = await DynamicDataApi.getUserSelect(val: int.parse(v));
                }catch(e){
                  userList = [];
                }
                setState(() { });
              }
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ):Container(),

          udtTbDocmentstock.status=="1"?
          CrySelect(
            label: '归还人员',
            dataList: userList,
            value: udtTbLendrecord.returnuserId,
            onSaved: (v) {
              udtTbLendrecord.returnuserId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ):Container(),

          udtTbDocmentstock.status=="1"?
          CrySelectDate(
            context,
            label: '归还日期',
            value: udtTbLendrecord.returndate,
            onSaved: (v) {
              udtTbLendrecord.returndate = v;
            },
          ):Container(),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: '确定',
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            UdtTbLendrecordOdooApi.lendOrReturn(udtTbLendrecord).then((ResponseBodyApi res) {
              if (!res.success!) {
                // CryUtils.message(res.message!);
                return;
              }
              udtTbDocmentstock.status == "0"?udtTbDocmentstock.status="1":udtTbDocmentstock.status="0";
              UdtTbDocmentstockOdooApi.saveOrUpdate(udtTbDocmentstock.toOdooMap()).then((ResponseBodyApi res) {
                if (!res.success!) {
                  return;
                }
                Navigator.pop(context, true);
                CryUtils.message(S.of(context).saved);
              });
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(udtTbDocmentstock.status=="1" ? "归还" : "借阅"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}